package com.acando.mate;

import java.util.List;

import com.acando.mate.models.Place;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class PlacesAdapter extends ArrayAdapter<Place>{


	public PlacesAdapter(Context context, List<Place> objects) {
		super(context, R.layout.places_item, objects);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) getContext()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View rowView = inflater.inflate(R.layout.places_item, parent, false);
		
		TextView places_name = (TextView) rowView
				.findViewById(R.id.places_name);
	
		TextView street = (TextView) rowView
				.findViewById(R.id.places_street_view);
		TextView city = (TextView) rowView
				.findViewById(R.id.places_city_view);
		TextView telNr = (TextView) rowView
				.findViewById(R.id.places_telnr_view);
		telNr.setOnClickListener(phoneClickListener);
		TextView faxNr = (TextView) rowView
				.findViewById(R.id.places_faxnr_view);
		
		
		places_name.setText(getItem(position).getName());
		street.setText(getItem(position).getStreet());
		city.setText(getItem(position).getCity());
		telNr.setText(getItem(position).getTelNr());
		faxNr.setText(getItem(position).getFaxNr());
		 
		return rowView;
	}

	private OnClickListener phoneClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			try {

				String phoneNumber = ((TextView) v).getText().toString();
				Intent callIntent = new Intent(Intent.ACTION_CALL);
				callIntent.setData(Uri.parse(phoneNumber));
				getContext().startActivity(callIntent);
			} catch (Exception e) {
				Log.e("WorkersAdapter",
						"do not use phoneClickListener if you have no Phone in text-field");
			}
		}
	};

}
